<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <template v-slot:before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template v-slot:after>
          <el-button type="warning" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" @click="exportData">excel导出</el-button>
          <el-button type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 表格和分页 -->
      <el-card v-loading="loading">
        <el-table :data="list" border="">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <img
                slot="reference"
                v-imageerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <!-- 作用域插槽 -->
            <!--  <template slot-scope='obj'></template>  -->
            <!--  <template v-slot="obj">{{ obj.row.timeOfEntry }}</template>  -->
            <template v-slot="{row}">{{ row.timeOfEntry|formatDate }}</template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${ row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            layout="prev, pager, next"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <!-- 新增员工 -->
      <add-employee :show-dialog.sync="showDialog" />
      <!-- 二维码 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog" @close="imgUrl=''">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 角色 -->
      <assignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee'
import formatDate from '@/filters'
import QrCode from 'qrcode'
import assignRole from './components/assign-role.vue'

export default {
  components: {
    AddEmployee,
    assignRole
  },
  data() {
    return {
      list: [], // 表格内容(接收数据)
      page: {
        page: 1, // 当前页码
        size: 10,
        total: 0 // 总数
      },
      loading: false, // 显示遮罩层
      showDialog: false, // 弹出层不显示
      showCodeDialog: false, // 二维码查看弹框不显示
      imgUrl: '', // 预览头像地址
      showRoleDialog: false, // 角色弹层不显示
      userId: null // 用户id
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    changePage(newPage) { // currentPage 改变时会触发
      this.page.page = newPage
      this.getEmployeeList()
    },
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    formatEmployment(row, column, cellValue, index) { // 格式化聘用形式 // cellValue就是1就是正式
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async deleteEmployee(id) {
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id)
        // 如果不是第一页，且只有一个元素，删除成功，则需要把页码-1，重新拉取列表
        if (this.list.length === 1 && this.page.page !== 1) {
          this.page.page--
        }
        this.getEmployeeList()
        this.$message.success('删除员工成功')
      } catch (err) {
        console.log(err)
      }
    },
    exportData() { // 导出Excel
      // 因为数据中的key是英文，想要导出的表头是中文的话，需要将中文和英文做对应
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => { // 懒加载
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows) // 返回的data就是 要导出的结构
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers), // 导出数据的表头(默认[])
          data, // 导出的具体数据(默认[[]])
          filename: '员工信息表', // 导出文件名
          autoWidth: true, // 单元格是否要自适应宽度(默认true)
          bookType: 'xlsx', // 导出文件类型(默认xlsx)
          multiHeader, // 复杂表头
          merges // 合并选项
        })
      })
      // import('@/vendor/Export2Excel').then(excel => {
      //   excel.export_json_to_excel({
      //     header: ['姓名', '工资'], // 表头 必填
      //     data: [['张三', 3000], ['李四', 5000]], // 具体数据 必填
      //     filename: '员工工资表' // 非必填
      //   })
      // })
    },
    formatJson(headers, rows) {
      return rows.map(item => { // item是一个对象{mobile:13222,username:'张三' }
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]]) // 日期格式化
          } else if (headers[key] === 'formOfEmployment') { // 聘用形式
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]] // ['13222','张三','','']
        })
      })
    },
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          // 二维码用法QrCode.toCanvas(dom, info)   dom为一个canvas的dom对象， info为转化二维码的信息 将canvas标签放到dialog的弹层中
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    editRole(id) {
      this.userId = id
      this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
      this.showRoleDialog = true
    }

  }

}
</script>

<style>

</style>
